<?php

namespace App\Containers\AppSection\User\Actions;

use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Ship\Exceptions\InternalErrorException;
use App\Ship\Exceptions\NotFoundException;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Exceptions\Exception;
use App\Ship\Parents\Requests\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ChangePasswordAction extends Action
{
    public function run(Request $request): void
    {
        $user = Auth::user();
        $old_password = $request->getInputByKey('old_password');
        $new_password = $request->getInputByKey('new_password');

        if (!Hash::check($old_password, $user->password)) {
            throw new NotFoundException('Пароль не найден!');
        }
        try {
            $user->forceFill([
                'password' => Hash::make($new_password),
            ])->save();
        } catch (Exception $e) {
            throw new InternalErrorException();
        }


        app(CreateLogTask::class)->run($request->profile()->id, 'Смена пароля', 'user');
    }
}
